﻿using Microsoft.ClearScript.V8;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using System.Web.UI.WebControls;
using 挂号.compent;

namespace 挂号
{
    public class Http
    {
        private string username;
        private string password;
        private string Unitid;
        private HttpClient httpClient;
        private V8ScriptEngine engine;

        public Http()
        {
            this.username = "005005-102054";
            this.password = "123456";
            this.Unitid = "005005";
            this.httpClient = new HttpClient();
            this.engine = new V8ScriptEngine();
            this.engine.Execute(@"
                  function encry(e, t) {
                        function StringToHex(e) {
                            for (var t = '', n = 0; n < e.length; n++) t += '' + e.charCodeAt(n).toString(16);
                            return t
                        }
                        var n = e.length, r = [], o = '', i = n % t.length;
                        if (i > 0) {
                            r.push(e);
                            for (var a = t.length - i, s = 0; s < a; s++) r.push(' ');
                            o = r.join('')
                        } else o = e;
                        for (var u = 0, c = [], l = 0; l < o.length; l++) {
                            u >= t.length && (u = 0);
                            var f = o.charAt(l).charCodeAt(0), h = parseInt(t.charAt(u), 16), p = f ^ h;
                            c.push(String.fromCharCode(p)), u++
                        }
                        return StringToHex(c.join('').replace(/^\s+|\s+$/g, ''));
                    }
            ");
        }


        //获取param_D
        private async Task<String> Login_step1()
        {
            HttpResponseMessage resp = await this.httpClient.GetAsync($"http://192.168.100.37/sj_web_app/webapi/UserMgr/GetCode?UserId={this.username}&axios_get_timeId={DateTimeOffset.Now.ToUnixTimeSeconds()}");
            string res = await resp.Content.ReadAsStringAsync();
            Root_Step1 json_step1 = JsonConvert.DeserializeObject<Root_Step1>(res);
          
            return json_step1.D;
        }

        private async Task<String> Login_step2(string param_D)
        {
            //密码先md5加密
            string md5pwd = GetMD5Hash(this.password);
            //再与param_D进行加密
            string encry_str = this.engine.Script.encry(md5pwd, param_D);
            HttpResponseMessage res = await this.httpClient.GetAsync($"http://192.168.100.37/sj_web_app/webapi/UserMgr/Login2?userid={this.username}&password={encry_str}&hostMac=1001&hostName=&hostAddress=&unitId=005005&axios_get_timeId={DateTimeOffset.Now.ToUnixTimeSeconds()}");
            //最后获取
            return await res.Content.ReadAsStringAsync();
        }

        //获取sjID,后面全局需要使用
        private async Task<String> Login_step3()
        {
            HttpResponseMessage res = await this.httpClient.GetAsync($"http://192.168.100.37/sj_web_app/webapi/UserMgr/GetASJID?axios_get_timeId={DateTimeOffset.Now.ToUnixTimeSeconds()}");
            string repon = await res.Content.ReadAsStringAsync();
            Root_Step1 step = JsonConvert.DeserializeObject<Root_Step1>(repon);
            return step.D;
        }



        //通过身份证信息查询病人信息
        private async Task<PatientInfo> QueryPatientInfo(PatientInfo info, String sj_id)
        {
            List<KeyValuePair<String, String>> httplist = new List<KeyValuePair<String, String>>()
            {
                new KeyValuePair<string, string>("SourceType", "1"),
                new KeyValuePair<string, string>("PassType","01"),
                new KeyValuePair<string, string>("PassNumber",info.cardNum),
                new KeyValuePair<string, string>("PatientId",""),
                new KeyValuePair<string, string>("ExtParam",""),
                new KeyValuePair<string, string>("axios_get_timeId",DateTimeOffset.Now.ToUnixTimeSeconds().ToString()),


            };


            FormUrlEncodedContent httpcontent = new FormUrlEncodedContent(httplist);
            HttpResponseMessage res = await this.httpClient.PostAsync($"http://192.168.100.37/sj_web_app/webapi/CISPatientCard/GetPatInfoByPass?_a_sj_id_={sj_id}", httpcontent);
            string serial =  await res.Content.ReadAsStringAsync();
            QueryPatient pat2 = JsonConvert.DeserializeObject<QueryPatient>(serial);
            PatientInfores temp = pat2.D[0];
            info.PatientId = temp.PatientId;
            info.Name = temp.Name;
            info.AgeText = temp.AgeText;
            info.Sex = temp.Sex.ToString();
            info.CardNo = temp.CardNo;
            info.cardNum = info.cardNum;
            info.address = temp.Address1Name;
            info.birth = temp.Birthday.ToString("yyyy-MM-dd");
            info.ContactsPhone = temp.ContactsPhone;

            return info;
        }

        //刮号之前需要再次进行患者信息更新
        private async Task<String> UpdatePatientInfo(PatientInfo info, String sj_id)
        {
            DateTime now = DateTime.Now;
            JObject entity_card = new JObject();
            JObject entity_pat = new JObject();
            entity_card.Add("UnitId", this.Unitid);
            entity_card.Add("CardNo", info.cardNum);
            entity_card.Add("CardType", 27);
            entity_card.Add("PatientId", info.PatientId);
            entity_card.Add("Reliability", 2);
            entity_card.Add("Name", info.Name);
            entity_card.Add("Sex", info.Sex);
            entity_card.Add("ReMan", this.username);
            entity_card.Add("MrType", 0);

            entity_pat.Add("UnitId", this.Unitid);
            entity_pat.Add("PatientId", info.PatientId);
            entity_pat.Add("PassType", "01");
            entity_pat.Add("PassNumber", info.cardNum);
            entity_pat.Add("CardType", 7);
            entity_pat.Add("CardNo", info.cardNum);
            entity_pat.Add("Name", info.Name);
            entity_pat.Add("Sex", info.Sex);
            entity_pat.Add("Birthday", info.birth);
            entity_pat.Add("BirthTime", info.birth);
            entity_pat.Add("AgeText", info.AgeText); //
            entity_pat.Add("Reliability", "2");
            entity_pat.Add("AgeYear", "");
            entity_pat.Add("AgeMonth", "");
            entity_pat.Add("AgeDay", ""); //天
            entity_pat.Add("GetAgeDate", now.ToString("yyyy-MM-ddTHH:mm:ssZ"));
            entity_pat.Add("PhoneCode", info.ContactsPhone);
            entity_pat.Add("MotherName", "");
            entity_pat.Add("GuardianType", "");
            entity_pat.Add("guardianIdType", "01");
            entity_pat.Add("guardianId", "");
            entity_pat.Add("MarriageCode", "");
            entity_pat.Add("NationCode", "");
            entity_pat.Add("NativePlace", "");
            entity_pat.Add("OccupationCode", "");
            entity_pat.Add("Nationality", "");
            entity_pat.Add("Address", info.address);
            entity_pat.Add("Address1", "420000");
            entity_pat.Add("Address2", "421100");
            entity_pat.Add("Address3", "421182");
            entity_pat.Add("Address4", "");
            entity_pat.Add("Address5", "");
            entity_pat.Add("Address6", "");
            entity_pat.Add("PlaceType", "0");
            entity_pat.Add("ContactsName", info.Name);
            entity_pat.Add("ContactsPhone", info.ContactsPhone);
            entity_pat.Add("ContactsRelation", "");
            entity_pat.Add("CreateTime", now.ToString("yyyyMMddHHmmss"));
            entity_pat.Add("ComeSource", "");
            entity_pat.Add("ComeDate", now.ToString("yyyy-MM-ddTHH:mm:ssZ"));
            entity_pat.Add("WorkUnit", "");
            entity_pat.Add("RegAddress", "");


            List<KeyValuePair<String, String>> list_content = new List<KeyValuePair<String, String>>()
            {
                new KeyValuePair<string, string>("UnitId",this.Unitid ),
                new KeyValuePair<string, string>("entity_card",entity_card.ToString()),
                new KeyValuePair<string, string>("entity_pat",entity_pat.ToString()),
                new KeyValuePair<string, string>("FeeCard",""),
                new KeyValuePair<string, string>("FeeCase",""),
                new KeyValuePair<string, string>("FeeCardCode","001-7926"),
                new KeyValuePair<string, string>("FeeCaseCode","001-1002"),
                new KeyValuePair<string, string>("UserDeptId","005005-078"),
                new KeyValuePair<string, string>("UserId",this.username),
                new KeyValuePair<string, string>("DeptId",info.DeptId),
                new KeyValuePair<string, string>("DoctorId",""),
                new KeyValuePair<string, string>("PatientId",info.PatientId),
                new KeyValuePair<string, string>("VisitId",""),
                new KeyValuePair<string, string>("RegisterType","005005-5"),
                new KeyValuePair<string, string>("AtNoon","下午"),
                new KeyValuePair<string, string>("RegisterDate",now.ToString("yyyy-MM-dd")),
                new KeyValuePair<string, string>("SourceType","1"),
                new KeyValuePair<string, string>("axios_get_timeId",DateTimeOffset.Now.ToUnixTimeSeconds().ToString()),

            };
            FormUrlEncodedContent httpcontent = new FormUrlEncodedContent(list_content);
            Debug.WriteLine(list_content.ToString());
            HttpResponseMessage res = await this.httpClient.PostAsync($"http://192.168.100.37/sj_web_app/webapi/CISRegisterDetail/PatAndCardSave?_a_sj_id_={sj_id}", httpcontent);
            return await res.Content.ReadAsStringAsync();
        }



        //注册并锁定号源
        private async Task<String> RegAndLockSourceSave(PatientInfo info, String sj_id)
        {
            JObject entity = new JObject();
            entity.Add("RegisterId", "");
            entity.Add("UnitId", this.Unitid);
            entity.Add("RegisterDate", DateTime.Now.ToString("yyyy-MM-ddT00:00:00.000Z"));
            entity.Add("AtNoon", "全天");
            entity.Add("ValidMark",0);
            entity.Add("TimeInterval", "");
            entity.Add("DeptId", info.DeptId);
            entity.Add("DeptName", info.DeptName);
            entity.Add("DoctorId", "");
            entity.Add("DoctorName", "");
            entity.Add("RegisterType", "005005-5");
            entity.Add("PatientId", info.PatientId);
            entity.Add("Name", info.Name);
            entity.Add("AgeText", info.AgeText);
            entity.Add("Sex", info.Sex);
            entity.Add("ChargeMark", 0);
            entity.Add("greenSource","");
            entity.Add("PatientTypeSource", "");
            entity.Add("FcTypeMark", 0);
            entity.Add("FcTypeCode", "");
            entity.Add("FcType", "");
            entity.Add("FcIdType", "");
            entity.Add("FcIdNo", "");
            entity.Add("AppointmentMark", 0);
            entity.Add("RegisterLocation", 1);
            entity.Add("AccountType", "005-1");
            entity.Add("GiveMark", 0);
            entity.Add("PracticeDeptId", info.DeptId);
            entity.Add("PracticeDeptName", info.DeptName);
            entity.Add("PatDeptId", info.DeptId);
            entity.Add("PatDeptName", info.DeptName);
            entity.Add("CardNo", info.CardNo);
            entity.Add("CardType", 27);
            entity.Add("PlatformId", "");
            entity.Add("DayPlanId", "");
            entity.Add("SourceId", "");
            entity.Add("PlatformOrderid", "");
            entity.Add("OutPatientNo", info.CardNo);
            entity.Add("PreBegindt", null);
            entity.Add("PreEnddt", null);
            entity.Add("NoonMark", 0);
            entity.Add("TimeName", "");
            entity.Add("ClassName", "");
            entity.Add("ApptClassId", "");

        
            JObject entityFee = new JObject();
            entityFee.Add("FeeCode", "005001-1001");
            entityFee.Add("Price", "0.00");
            entityFee.Add("OtherCode1", "");
            entityFee.Add("OtherPrice1", "0.00");
            entityFee.Add("OtherCode2", "");
            entityFee.Add("OtherPrice2", "0.00");
            entityFee.Add("OtherCode3", "");
            entityFee.Add("OtherPrice3", "0.00");

            List<KeyValuePair<String, String>> list = new List<KeyValuePair<String, String>>()
            {
                new KeyValuePair<String,String>("UnitId",this.Unitid),
                new KeyValuePair<String,String>("entity",entity.ToString()),
                new KeyValuePair<String,String>("entityFee",entityFee.ToString()),
                new KeyValuePair<String,String>("CostIds","[]"),
                new KeyValuePair<String,String>("UserId",this.username),
                new KeyValuePair<String,String>("ScheduleId",""),
                new KeyValuePair<String,String>("SourceType","1"),
                new KeyValuePair<String,String>("axios_get_timeId",DateTimeOffset.Now.ToUnixTimeSeconds().ToString()),
            };

            FormUrlEncodedContent content = new FormUrlEncodedContent(list);
            HttpResponseMessage res = await this.httpClient.PostAsync($"http://192.168.100.37/sj_web_app/webapi/CISRegisterDetail/RegAndLockSourceSave?_a_sj_id_={sj_id}", content);
            return await res.Content.ReadAsStringAsync();
        }

        //加载订单信息
        private async Task<String> LoadOrder(PatientInfo info, String sj_id)
        {
            JObject json = new JObject();
            json.Add("unitid", this.Unitid);
            json.Add("OutPatientNo", info.cardNum);
            json.Add("PatientName", info.Name);
            json.Add("AcceptType", 0);
            json.Add("GhVisitId", info.GhVisitId);

            List<KeyValuePair<string, string>> list = new List<KeyValuePair<string, string>>()
            {
                new KeyValuePair<string, string> ( "value",json.ToString()),
                new KeyValuePair<string, string> ( "axios_get_timeId",DateTimeOffset.Now.ToUnixTimeSeconds().ToString())
            };
            FormUrlEncodedContent content = new FormUrlEncodedContent(list);

            HttpResponseMessage message = await this.httpClient.PostAsync($"http://192.168.100.37/sj_web_app/webapi/FeeOutAccount/LoadOrders?_a_sj_id_={sj_id}", content);
            String res = await message.Content.ReadAsStringAsync();
            return res;
        }

        //获取dowork相关参数
        private async Task<String> GetUIInterFaceConfigInf(String sj_id)
        {
            List<KeyValuePair<String, String>> list = new List<KeyValuePair<String, String>>()
            {

                new KeyValuePair<String, String> ("UnitID","005005"),
                new KeyValuePair<String, String> ("MouldName","门诊收费接口"),
                new KeyValuePair<String, String> ("EventName","门诊收费医保预结算前"),
                new KeyValuePair<String, String> ("axios_get_timeId",DateTimeOffset.Now.ToUnixTimeSeconds().ToString()),
            };
            FormUrlEncodedContent content = new FormUrlEncodedContent(list);
            HttpResponseMessage message = await this.httpClient.PostAsync($"http://192.168.100.37/sj_web_app/webapi/SYSUiEventExtendSet/GetUIInterfaceConfigInf?_a_sj_id_={sj_id}", content);
            string res = await message.Content.ReadAsStringAsync();
            return res;

        }


        //交易进行
        private async Task<String> DoWork(PatientInfo info, String sj_id,int index)
        {
            JObject json = new JObject();
            json.Add("UnitId", this.Unitid);
            json.Add("UserId", this.username);
            json.Add("StationId", info.UPdateStation);
            json.Add("BatchOrdinalNo", info.acceptBatchCode);
            json.Add("MouldName", "门诊收费接口");
            json.Add("EventName", "门诊收费医保结算前");
            JObject OtherReqInfo = new JObject();
            OtherReqInfo.Add("BizCode", "Accounting");
            OtherReqInfo.Add("PatientNo", info.CardNo);
            OtherReqInfo.Add("AccountType", "005-1");
            OtherReqInfo.Add("AccountTypeName", "自费");
            OtherReqInfo.Add("PatientName", info.Name);
            OtherReqInfo.Add("VisitId", "");
            OtherReqInfo.Add("UnitId", this.Unitid);
            OtherReqInfo.Add("AccountNo", "");
            OtherReqInfo.Add("AcceptOrdinalNo", "");
            JObject ReturnInf = new JObject();
            ReturnInf.Add("OutMedAccountId", "");
            ReturnInf.Add("InterfaceType", 2);
            ReturnInf.Add("AccountType", "005-1");
            ReturnInf.Add("TotalExpenses", 0);
            ReturnInf.Add("AllAccount", 0);
            ReturnInf.Add("AllSelfFee", 0);
            ReturnInf.Add("AccountPayInf", new JArray());
     
            json.Add("Details", JArray.FromObject(info.Details));
         
            ReturnInf.Add("ChargeDetails", new JArray());
            ReturnInf.Add("ReturnDetails", new JArray());
            ReturnInf.Add("ReturnChargeDetails", new JArray());

            json.Add("OtherReqInf", OtherReqInfo);
            json.Add("ReturnInf", ReturnInf);

            D2[] conf = JsonConvert.DeserializeObject<D2[]>(info.Conf);

            json.Add("Conf", JsonConvert.SerializeObject(conf[index], Formatting.Indented));

            List<KeyValuePair<String, String>> list = new List<KeyValuePair<string, string>>()
            {
                new KeyValuePair<string, string>("ReqJson",json.ToString()),
                new KeyValuePair<string, string>("axios_get_timeId",DateTimeOffset.Now.ToString()),
            };

            FormUrlEncodedContent content = new FormUrlEncodedContent(list);
            HttpResponseMessage message = await this.httpClient.PostAsync($"http://192.168.100.37/sj_web_app/webapi/FEERegister/dowork?_a_sj_id_={sj_id}", content);
            string res = await message.Content.ReadAsStringAsync();
            Debug.WriteLine($"doWork 返回值:{res}");
            return res;
        }

        //开始交易
        private async Task<String> BeginFeeAccountMain(String sj_id)
        {
            JObject json = new JObject();
            json.Add("UnitId", this.Unitid);
            json.Add("OutPatientNo", "");
            json.Add("AccountNo", "");
            json.Add("MThirdPay", "");
            json.Add("MMedicaling", "");
            json.Add("MMedical", "");
            json.Add("MMedicaled", "");
            json.Add("MCallback", "");
            List<KeyValuePair<String, String>> list = new List<KeyValuePair<String, String>>()
            {
                new KeyValuePair<string, string>("value",json.ToString()),
                new KeyValuePair<string, string>("axios_get_timeId",DateTimeOffset.Now.ToUnixTimeSeconds().ToString()),
            };
            FormUrlEncodedContent content = new FormUrlEncodedContent(list);
            HttpResponseMessage message = await this.httpClient.PostAsync($"http://192.168.100.37/sj_web_app/webapi/FeeOutAccount/BeginFeeAccountMain?_a_sj_id_={sj_id}", content);
            string res = await message.Content.ReadAsStringAsync();
            return res;
        }

        //保存订单
        private async Task<String> SaveOrder(PatientInfo info, String sj_id)
        {
            JObject json = new JObject();
            json.Add("FactOperator", this.username);
            json.Add("Operator", this.username);
            json.Add("Amount", 0);
            json.Add("MedAccount", 0);
            json.Add("ThirdAccount", 0);
            json.Add("HospitalPay", 0);
            json.Add("SelfCardType", 0);
            json.Add("SelfCardPay", 0);
            json.Add("OtherCardType", 0);
            json.Add("OtherCardPay", 0);
            json.Add("CashPay", 0);
            json.Add("RoundVal", 0);
            json.Add("AcceptMoney", 0);
            json.Add("RetrunMoney", 0);
            json.Add("ChargeDetails", new JArray());
            json.Add("AccountType", "005-1");
            json.Add("AcceptBatchCode", info.acceptBatchCode);
            json.Add("OutPatientNo", info.CardNo);
            json.Add("UnitId", this.Unitid);
            json.Add("VisitId", "");
            json.Add("PatientName", info.Name);
            json.Add("Details", JArray.FromObject(info.Details));
            json.Add("SelfCardCode", info.CardNo);
            json.Add("InvoiceType", "");
            json.Add("InvoiceCode", "");
            json.Add("OtherCardPayOrdinal", "");
            json.Add("OtherCardCode", "");
            json.Add("AccountNo", info.AccountNo);
            json.Add("AcceptType", 0);
            List<KeyValuePair<String, String>> list = new List<KeyValuePair<string, string>>()
            {
                new KeyValuePair<string, string>("value",json.ToString()),
                new KeyValuePair<string, string>("axios_get_timeId",DateTimeOffset.Now.ToUnixTimeSeconds().ToString()),
            };
            FormUrlEncodedContent content = new FormUrlEncodedContent(list);
            HttpResponseMessage message = await this.httpClient.PostAsync($"http://192.168.100.37/sj_web_app/webapi/FeeOutAccount/SaveOrders?_a_sj_id_={sj_id}", content);
            string res = await message.Content.ReadAsStringAsync();
            Debug.WriteLine($"saveOrder:{res}");
            return res;
        }

        //结束交易
        private async Task<String> EndFeeAccountMain(PatientInfo info, String sj_id)
        {
            JObject json = new JObject();
            json.Add("AccountNo", info.AccountNo);
            json.Add("AccountStatus", "0");
            json.Add("OptType", null);
            json.Add("AccountTime", "9999-12-31T23:59:59.9999999");
            json.Add("FeeType", 1);
            json.Add("OutPatientNo", "");
            json.Add("PatientName", null);
            json.Add("Amount", 0);
            json.Add("RoundingAmount", 0);
            json.Add("AccountType", null);
            json.Add("MedicalAmount", 0);
            json.Add("HospAmount", 0);
            json.Add("CardAmount", 0);
            json.Add("SelfAmount", 0);
            json.Add("Cash", 0);
            json.Add("PreAcctNumber", null);
            json.Add("PreAmount", 0);
            json.Add("ThirdAmount", 0);
            json.Add("ThirdType", null);
            json.Add("ThirdKey", null);
            json.Add("StationId", null);
            json.Add("DailyId", null);
            json.Add("RelFeeId", null);
            json.Add("AcceptType", null);
            json.Add("OperatorCode", null);
            json.Add("UnitId", "005005");
            json.Add("DailyTime", null);
            json.Add("FactOperator", null);
            json.Add("PrePayType", null);
            json.Add("ThirdAccount", 0);
            json.Add("ThirdAcctNumber", null);
            json.Add("GbAmount", 0);
            json.Add("AutoRowid", 0);
            json.Add("FeeOutAccountoid", null);
            json.Add("CreateOn", null);
            json.Add("UpdateOn", null);
            json.Add("DeletedMark", 0);
            json.Add("CreateBy", null);
            json.Add("UpdateBy", null);
            json.Add("CreateStation", null);
            json.Add("UpdateStation", null);
            json.Add("SrvId", null);
            json.Add("XmlData", null);
            json.Add("VisitId", null);
            json.Add("MBegin", "2024-08-22T18:50:46.321");
            json.Add("MThirdPay", "0");
            json.Add("MMedicaling", "0");
            json.Add("MMedical", "0");
            json.Add("MMedicaled", "0");
            json.Add("MCallback", "0");
            json.Add("MEnd", null);

            List<KeyValuePair<String, String>> list = new List<KeyValuePair<String, String>>()
            {
                new KeyValuePair<String,String>("value",json.ToString()),
                new KeyValuePair<String,String>("axios_get_timeId",DateTimeOffset.Now.ToUnixTimeSeconds().ToString()),
            };
            FormUrlEncodedContent content = new FormUrlEncodedContent(list);
            HttpResponseMessage message = await this.httpClient.PostAsync($"http://192.168.100.37/sj_web_app/webapi/FeeOutAccount/EndFeeAccountMain?_a_sj_id_={sj_id}", content);
            string res = await message.Content.ReadAsStringAsync();
            return res;
        }

        private async Task<HttpResponseMessage> PutAccount(PatientInfo info,String sj_id)
        {
            JObject json = new JObject();
            json.Add("UnitId",this.Unitid);
            json.Add("UserId", this.username);
            json.Add("StationId", info.UpdateStation);
            json.Add("BatchOrdinalNo", info.acceptBatchCode);
            json.Add("MouldName", "门诊收费接口");
            json.Add("EventName", "门诊收费结算后");

            JObject OtherReqInf = new JObject();
            OtherReqInf.Add("UnitId", this.Unitid);
            OtherReqInf.Add("OutPatientNo", info.PatiendId);
            OtherReqInf.Add("PaitentName", info.Name);
            OtherReqInf.Add("AccountNo", info.AccountNo);
            json.Add("OtherReqInf", OtherReqInf);
            json.Add("ReturnInf", new JObject());
            json.Add("Conf", info.endOutaccountConf);

            List<KeyValuePair<String, String>> list = new List<KeyValuePair<String, String>>()
            {
                new KeyValuePair<string, string>("ReqJson",json.ToString()),
                new KeyValuePair<string, string>("asios_get_timeId",DateTimeOffset.Now.ToUnixTimeSeconds().ToString()),
            };
            FormUrlEncodedContent content = new FormUrlEncodedContent(list);
            return await this.httpClient.PostAsync($"http://192.168.100.37/sj_web_app/webapi/FeeSelfpayMdtrt/OutAccount?_a_sj_id_={sj_id}", content);
        }


        private async Task<String> OutAccount(PatientInfo info ,String sj_id)
        {
            JObject param = new JObject();
            param.Add("UnitId", this.Unitid);
            param.Add("UserId", this.username);
            param.Add("StationId", info.UpdateStation);
            param.Add("BatchOrdinalNo", info.acceptBatchCode);
            param.Add("MouldName", "门诊收费接口");
            param.Add("EventName", "门诊收费结算后");
            JObject OtherReqInf = new JObject();
            OtherReqInf.Add("UnitId", this.Unitid);
            OtherReqInf.Add("OutPatientNo", info.PatiendId);
            OtherReqInf.Add("PaitentName", info.Name);
            OtherReqInf.Add("AccountNo", info.AccountNo);
            param.Add("OtherReqInf", OtherReqInf);
            param.Add("ReturnInf", new JObject());
            param.Add("Conf", info.endOutaccountConf);

            List<KeyValuePair<String, String>> list = new List<KeyValuePair<string, string>>()
            {
                new KeyValuePair<string, string>("ReqJson",param.ToString()),
                new KeyValuePair<string, string>("asios_get_timeId",DateTimeOffset.Now.ToUnixTimeSeconds().ToString()),
            };
            FormUrlEncodedContent content = new FormUrlEncodedContent(list);
            HttpResponseMessage message = await this.httpClient.PostAsync($"http://192.168.100.37/sj_web_app/webapi/FeeSelfpayMdtrt/OutAccount?_a_sj_id_={sj_id}",content);
            string res = await message.Content.ReadAsStringAsync();
            return res;
        }


        static string GetMD5Hash(string input)
        {
            using (MD5 md5 = MD5.Create())
            {
                byte[] inputBytes = Encoding.UTF8.GetBytes(input);
                byte[] hashBytes = md5.ComputeHash(inputBytes);
                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < hashBytes.Length; i++)
                {
                    sb.Append(hashBytes[i].ToString("X2"));
                }
                return sb.ToString();
            }
        }


        //对外暴露使用的方法,用来注册挂号
        public async Task<PatientInfo> Register(PatientInfo info)
        {
            //1.执行登陆步骤
            string param_D =   await this.Login_step1();
            string step2 = await this.Login_step2(param_D);
            string sj_id = await this.Login_step3();
         
            PatientInfo res = await this.QueryPatientInfo(info, sj_id);
       
            string upinfo = await this.UpdatePatientInfo(res, sj_id);

            Debug.WriteLine(JsonConvert.SerializeObject(res,Formatting.Indented));
            Debug.WriteLine(upinfo);
            string upinfo1 = await this.RegAndLockSourceSave(res, sj_id);
            Reginfo reginfo = JsonConvert.DeserializeObject<Reginfo>(upinfo1);
            res.GhVisitId = reginfo.D.FeeIds[0];
            res.UpdateStation = "005005-243";
            //加载订单
            string loadorder = await this.LoadOrder(res,sj_id);
            Loadinfo loadinfo = JsonConvert.DeserializeObject<Loadinfo>(loadorder);
            res.acceptBatchCode = loadinfo.D.AcceptBatchCode;
            res.Details = loadinfo.D.Details;  
            string uiinter =  await this.GetUIInterFaceConfigInf(sj_id);
            UIInter uiinfo = JsonConvert.DeserializeObject<UIInter>(uiinter);
            res.Conf = JsonConvert.SerializeObject(uiinfo.D, Formatting.Indented); 
            //开始2次工作
            await this.DoWork(res,sj_id,0);
            await this.DoWork(res,sj_id,1);
            string begin = await this.BeginFeeAccountMain(sj_id);
            Begininfo begin3 = JsonConvert.DeserializeObject<Begininfo>(begin);
            res.AccountNo = begin3.D.AccountNo;

            await this.SaveOrder(res,sj_id);
            string endfee = await this.EndFeeAccountMain(res, sj_id);
            Debug.WriteLine(endfee);
            EndFeeAccount endfeeaccount = JsonConvert.DeserializeObject<EndFeeAccount>(endfee);
            Debug.WriteLine("###################");
            Debug.WriteLine(JsonConvert.SerializeObject(endfeeaccount.D, Formatting.Indented));
            res.endOutaccountConf = JsonConvert.SerializeObject(endfeeaccount.D, Formatting.Indented);

            string outaccount = await this.OutAccount(res, sj_id);
            return res;
        }


    }
    public class Root_Step1
    {
        public int C { get; set; }
        public string T { get; set; }
        public string D { get; set; }
    }


    public class PatientInfo
    {
        public String cardNum { get; set; }
        public String address { get; set; }
        public String birth { get; set; }
        public String PatientId { get; set; }
        public String Name { get; set; }
        public String ContactsPhone { get; set; }
        public String DeptId { get; set; }
        public String GhVisitId { get; set; }
        public String UPdateStation { get; set; }
        public String acceptBatchCode { get; set; }
        public String CardNo { get; set; }
        public Detail[] Details { get; set; }
        public String Conf { get; set; }
        public String AccountNo { get; set; }
        public String UpdateStation { get; set; }
        public String PatiendId { get; set; }
        public String endOutaccountConf { get; set; }
        public String DeptName { get; set; }
        public String AgeText { get; set; }
        public String Sex { get; set; }

    }
}
